package com.house.service;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.dao.OrderMapper;
import com.house.entity.Lease;
import com.house.entity.Order;
import com.house.entity.User;
import com.house.util.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * 订单模块服务层
 */
@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Autowired
    private LeaseService leaseService;


    public boolean saveOrUpdate(Order order) {
        if(StrUtil.isEmpty(order.getId())) {
            order.init();

            // 填充登录用户信息
            User user = LoginUtil.getLoginUser();
            order.setCreateUser(user.getId());
            order.setUsername(user.getUsername());

            // 根据租赁信息ID 查询房屋ID
            Lease lease = leaseService.getById(order.getLeaseId());
            order.setTitle(lease.getTitle());
            order.setHouseId(lease.getHouseId());

            // 计算价格
            int price = Integer.parseInt(lease.getPrice()) * Integer.parseInt(order.getLeaseTime());
            order.setPrice(String.valueOf(price));

            // 计算搬出时间
            DateTime dateTime = DateUtil.offsetMonth(Convert.toDate(order.getCheckInTime()), Integer.parseInt(order.getLeaseTime()));
            order.setCheckOutTime(dateTime.toDateStr());
        } else {
            order.setUpdateTime(DateUtil.now());
        }


        // 更新租赁信息状态为失效
        Lease lease = new Lease();
        lease.setId(order.getLeaseId());
        lease.setStatus("0");
        lease.setStartTime(order.getCheckInTime());
        lease.setEndTime(order.getCheckOutTime());
        leaseService.updateById(lease);

        return super.saveOrUpdate(order);
    }
}
